<template>
	<view class="container">
		<u-cell-group class="bg">
			<u-cell>
				<view slot="title" class="search-container">
					<u-icon name="map-fill" size="25" @click="getLocation"></u-icon>
					<u-search bgColor="#FFFFFF" show-action v-model="keyWord" @custom="goSearch" @change="goSearch"></u-search>
					<text @click="confirm">确定</text>
				</view>
			</u-cell>
			<view class="list-container" v-if="pois.length>1">
				<u-list>
					<u-list-item v-for="(item,index) in pois" :key="index">
						<view class="location-name" @click="toLocation(item)">{{item.name}}</view>
					</u-list-item>
				</u-list>
			</view>
		</u-cell-group>
		<view>
			<map id="gisMap" :markers="currMarker"  enable-poi show-location  @markertap="markerClick"></map>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				keyWord:'',
				currMarker:[],
				map:null,
				pois:[],
				timer:null,
				saveLocation:'',
				location:{},
			};
		},
		onLoad() {
			this.getLocation()
		},
		mounted(){
			console.log('初始化地图');
			this.map = uni.createMapContext("gisMap", this);
			// this.openConfirm()
		},
		watch: {
			keyWord(newValue, oldValue) {
				if(newValue == ''){
					this.pois = []
				}
			}
		},
		methods:{
			confirm(){
				if(this.saveLocation){
					uni.$emit("sendLocation",this.location)
					uni.redirectTo({
						url:"/pages/user/profileEdit?hasLocation="+true
					})
				}else{
					uni.showToast({
						title:'无效地址',
						icon:'none'
					})
				}
			},
			markerClick(e){
				uni.showModal({
					title:"确认",
					content:'选择地址:'+this.saveLocation,
					success: (res) => {
						if(res.confirm){
							console.log('用户选择了：',this.saveLocation);
							uni.$emit("sendLocation",this.location)
							uni.redirectTo({
								url:"/pages/user/profileEdit?hasLocation="+true
							})
						}else{
							console.log("用户取消了选择");
						}
					}
				})
			},
			// poitap: function(e){
			// 	console.log(e,"poitap")
			// 	var obj = e.detail
			// 	obj.id = "CFD"+Math.floor(10*Math.random())+Math.floor(40*Math.random())
			// 	obj.location = obj.longitude+","+obj.latitude
			// 	this.toLocation(obj)
			// 	console.log("+++++",obj);
			// 	this.goSearch(obj.name)
			// 	this.addMarkers(obj)
			// },
			toLocation:function(obj){
				// 改变地图中心位置
				console.log(obj);
				this.location = obj
				let point = obj.location.split(',')
				this.keyWord = obj.address || obj.name
				this.saveLocation = obj.pname+obj.cityname+obj.adname+obj.adname+obj.name || obj.address
				obj.longitude = point[0]
				obj.latitude = point[1]
				this.addMarkers(obj)
				this.map.moveToLocation({
					longitude:obj.longitude*1,
					latitude:obj.latitude*1,
					success:(res)=>{
						console.log('地图点移动至：',res);
					}
				})
				// 移动标记点并添加动画效果
				this.map.translateMarker({
				  markerId: obj.id,
				  autoRotate: true,
				  duration: 100,
				  destination: {
				    latitude:obj.location.split(',')[1],
				    longitude:obj.location.split(',')[0],
				  },
				  animationEnd() {
				    console.log('animation end')
				  }
				})
			},
			// 位置授权
			getAuthorizeInfo(){
			    uni.authorize({
			        scope: 'scope.userLocation',
			            success() { // 允许授权
							that.getLocationInfo();
			            },
			            fail(){    // 拒绝授权
			                that.openConfirm();
			                console.log("你拒绝了授权，无法获得周边信息")
			            }
			        })
			},
			openConfirm(){
					uni.showModal({
						title: '请求授权当前位置',
						content: '需要获取您的地理位置，请确认授权',
						success: (res)=> {
						    if (res.confirm) {
						        uni.openSetting();// 打开地图权限设置
						    } else if (res.cancel) {
								uni.showToast({
									title: '你拒绝了授权，无法获得周边信息',
									icon: 'none',
									duration: 1000
						        })
						    }
						}
					});
				},
				
			/**
			 * @description 添加点
			 * @param
			 * marker:{
				id:0,
				latitude,
				longitude,
				title:'当前位置',
				width:30,
				height:30,
				iconPath:"../../static/personal.png",
				label:{
					content:'',
					color:'#000000',
					textAlign:'left'
				} 
			 }   
			 *  
 			 * 
			*/
			addMarkers(marker){
				console.log('执行添加点');
					marker.title = marker.name
					marker.iconPath = "../../static/adopt-active.png"
					marker.width = 30
					marker.height = 30
					marker.id = Math.floor(10*Math.random())+marker.adcode || '',
					marker.id = marker.id*1
					marker.label = {
						content:marker.title,
						textAlign:'center',
						bgColor:'#1ecf76',
						borderRadius:8,
						padding:5,
						x:-50,
						y:0
					}
					this.currMarker = []
					this.currMarker.push(marker)
			},
			getLocation(){
				console.log('执行了获取位置');
				let that = this
				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					accuracy:'best',
					isHighAccuracy:true,
					success: function (res) {
						console.log('success->当前位置：',res);
						let latitude = res.latitude
						let longitude = res.longitude
						let vm = getCurrentPages()[0]
						setTimeout(()=>{
							console.log(longitude,latitude);
							that.map.moveToLocation({
								longitude:longitude,
								latitude:latitude,
								success:(res)=>{
									console.log('地图点移动至：',res);
								}
							})
						},1000)
						// vm.currMarker.push({
						// 	id:0,
						// 	latitude,
						// 	longitude,
						// 	title:'当前位置',
						// 	width:30,
						// 	height:30,
						// 	iconPath:"../../static/personal.png",
						// 	label:{
						// 		content:'',
						// 		color:'#000000',
						// 		textAlign:'left'
						// 	}
						// })
					},
					fail: (err) => {
						if(err){
							uni.showToast({
								icon:"error",
								title:"获取定位失败",
								complete: () => {
									setTimeout(()=>{
										that.openConfirm()
									},2000)
								}
							})
						}
					}
				});
			},
			goSearch(value){
				console.log(value);
				this.keyWord = value
				if(this.keyWord == ''){
					this.pois = []
					return
				}
				if(!this.timer){
					this.timer = setTimeout(()=>{
						uni.request({
							url:`https://restapi.amap.com/v3/place/text?keywords=${value}&key=9a6a2dd849a6417eea115e31b30c8485&extensions=all`,
							success: (res) => {
								if(res.statusCode == 200 && res.data.status != 0 ){
									this.pois = res.data.pois
								}else{
									uni.showToast({
										icon:'none',
										title:'搜索服务次数超额'
									})
								}
							}
						})
						this.timer = null
					},800)
				}
				
			},
		},
	}
</script>

<style lang="scss">
 .container{
	 .search-container{
		 display: flex;
		 align-items: center;
		 text{
			 padding: 0 3rpx;
			 margin-top: 1rpx;
			 color: #17cc17;
		 }
	 }
	#gisMap{
		width: 100%;
		height: 100vh;
	}
	.bg{
		background-color: #FFFFFF;
	}
	.list-container{
		width: 100%;
		max-height: 330rpx;
		overflow: auto;
		.location-name{
			padding: 20rpx;
			border-bottom: 2rpx solid #d9d9d9;
		}
	}
 }
</style>
